<template>
  <div>
    <div class="index-box">
      <div class="content-head">
        <div class="content-head-title">
          <a-button type="primary" icon="plus" style="margin-right: 8px;" @click="() => { ModalPop = true;ModalTitle = '添加工单'; }">添加</a-button>
        </div>
        <div class="content-head-extra">
          <a-select style="width:200px;margin-right: 16px;" :options="communityList" @change="onSearch($event,1)" placeholder="请选小区" />
          <a-range-picker style="width:200px;" @change="onSearch($event,2)"/>
          <a-input-search style="width:200px;" placeholder="请输入标签名称" enterButton @search="onSearch($event,3)"/>
        </div>
      </div>
      <div class="content-body">
        <s-table ref="table" :columns="columns" :data="dataSource" :loading="loading" rowKey="id" >
          <template slot="operation" slot-scope="text,record">
            <a-dropdown>
              <a class="ant-dropdown-link" href="javascript:void(0);">操作 <a-icon type="down" /></a>
              <a-menu slot="overlay" @click="operation($event,record)">
                <a-menu-item key="1">编辑</a-menu-item>
                <a-menu-item key="3">删除</a-menu-item>
              </a-menu>
            </a-dropdown>
          </template>
        </s-table>
      </div>
    </div>
    <a-modal :title="ModalTitle" destroyOnClose v-model="ModalPop" :width="600" @ok="submitLabels" :confirmLoading="labelsOperationLoading">
      <a-form :form="labelsForm" @submit="submitLabels">
        <a-form-item label="选择小区" :labelCol="{xs:{span:24},sm:{span:7}}" :wrapperCol="{xs:{span:24},sm:{span:15}}">
            <a-select  :options="communityList" placeholder="请选小区" v-decorator="['bd_info_id',{rules:[{required:true,message:'请选小区'}]}]"/>
        </a-form-item>
        <a-form-item label="标题" :labelCol="{xs:{span:24},sm:{span:7}}" :wrapperCol="{xs:{span:24},sm:{span:15}}">
          <a-input placeholder="请输入工单标题" v-decorator="['title',{rules:[{required:true,message:'请输入工单标题'}]}]" />
        </a-form-item>
        <a-form-item label="内容" :labelCol="{xs:{span:24},sm:{span:7}}" :wrapperCol="{xs:{span:24},sm:{span:15}}">
            <a-textarea placeholder="请输入内容" v-decorator="['content',{rules:[{required:true,message:'请输入内容'}]}]"  />        
        </a-form-item>
        <a-form-item label="图片" v-bind="col" extra="最多可上传5张图片，且图片大小不可超过2M。">
          <a-upload class="operation-file-uploader" name="file" accept="image/*" listType="picture-card" :action="baseURL + 'community/uploadPic?token=' + token" @preview="imgPreview" v-decorator="['work_image',{initialValue:[],valuePropName:'fileList',getValueFromEvent:imageUpload}]">
            <div v-if="typeof labelsForm.getFieldValue('work_image') === 'undefined' || labelsForm.getFieldValue('work_image').length < 5">
              <a-icon type="plus" />
              <div class="ant-upload-text">上传图片</div>
            </div>
          </a-upload>
          <a-modal :visible="imagePreviewVisible" :footer="null" @cancel="() => { imagePreviewVisible = false }">
            <img alt="example" style="width: 100%" :src="previewImage" />
          </a-modal>
        </a-form-item>
        <a-form-item label="截止处理时间" :labelCol="{xs:{span:24},sm:{span:7}}" :wrapperCol="{xs:{span:24},sm:{span:15}}">
          <a-date-picker  placeholder="截止处理时间" v-decorator="['limited_time',{rules:[{required:true,message:'截止处理时间'}]}]" />
        </a-form-item>
        <a-form-item label="工单进度" :labelCol="{xs:{span:24},sm:{span:7}}" :wrapperCol="{xs:{span:24},sm:{span:15}}">
          <a-select placeholder="工单进度"   v-decorator="['progress',{rules:[{required:true,message:'请选择工单进度'}]}]">
            <a-select-option  value="1">待分配</a-select-option>
            <a-select-option  value="2">待完成</a-select-option>
            <a-select-option  value="3">已完成</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item style="display: none;">
          <a-input  v-decorator="['id']" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
  
</template>

<script>
  import { ACCESS_TOKEN } from '@/store/mutation-types'
  import {STable} from '@/components'
  import moment from 'moment'
  export default {
    name: 'complaint-order',
    data() {
      return {
        times:'',
        token:this.$ls.get(ACCESS_TOKEN),
        baseURL:this.axios.defaults.baseURL,
        typeNameList:[{label:'全部标签',value:0},{label:'房屋标签',value:1},{label:'车位标签',value:2},{label:'车辆标签',value:3},{label:'住户标签',value:4}],
        typeNameText:{"1":'房屋',"2":'车位',"3":'车辆',"4":'住户'},
        columns:[
            {title:'编号',dataIndex:'id'},
            { title:'工单标题',dataIndex:'title' },
            { title: '小区',dataIndex:'bd_info_id_text' } ,
            { title: '创建时间',dataIndex:'createtime' },
            { title: '最后操作时间',dataIndex:'actiontime' },
            { title: '工单进度',dataIndex:'progress_text' },
            { title: '操作',dataIndex:'operation', scopedSlots:{customRender:'operation'} }
            ],
        loading:false,
        col:{
          labelCol:{xs:{span:24},sm:{span:8}},
          wrapperCol:{xs:{span:24},sm:{span:8}}
        },
        imagePreviewVisible:false,
        previewImage:'', // 图片预览
        baseExcDate:{pageNo:1,pageSize:10},
        queryParam:{},
        dataSource:parameter => {
          return this.getList(Object.assign(parameter, this.queryParam))
            .then(res => {
              return res
            })
        }, // 列数据
        labelsInfo:{}, // 标签信息
        labelsForm:this.$form.createForm(this),
        ModalTitle:'', // 添加or编辑标签弹窗文字
        ModalPop:false, // 添加or编辑标签弹窗
        labelsOperationLoading:false, // 添加or编辑标题弹窗确定按钮加载状态
        bindTitle:'', // 绑定标签标题
        bindPop:false, // 绑定标签弹窗
        bindDataLoading:true, // 绑定标签骨架屏加载状态
        bindForm:this.$form.createForm(this),
        bindDataList:[],
        bindUserForm:this.$form.createForm(this), // 绑定住户
        bindUserModal:false, // 绑定住户
        bindUserModalLoading:false, // 绑定住户loading
        fetching:false,
        communityList:[], // 小区列表
        bindUserList:[], // 住户列表
      }
    },
    components:{STable},
    mounted() {
      this.getCommunity();
    },
    methods:{
      getList(param) {
        this.loading = true;
        return new Promise((resolve, reject) => {
          this.axios({
            method:'post',
            url:'/work/getList',
            data:Object.assign(param,{token:this.token,type:2})
          }).then(res => {
            resolve(res.data);
          }).catch(err => {
            this.$message.error('服务器发生错误...',2);
          }).finally(() => {
            this.loading = false;
          })
        })
      },
      // 筛选
      onSearch(val,type) {
        if(type == 1) {
            this.queryParam['bd_info_id'] = val;
        }else if(type==2){
            this.queryParam['start_time'] = val[0].format('YYYY-MM-DD');
            this.queryParam['end_time'] = val[1].format('YYYY-MM-DD');
        }else{
            this.queryParam['name'] = val;
            this.$refs.table.refresh(true);
        }
      },
      // 添加or编辑标签
      submitLabels(e) {
        e.preventDefault();
        this.labelsForm.validateFields((err, values) => {
          if (err) {
            for (let key in err) {
              for (let item of err[key]['errors']) return this.$message.warning(item['message'], 2)
            }
          }
          values.limited_time=values.limited_time.format('YYYY-MM-DD')
          values.type=2
          Object.assign(values,{token:this.token});
          this.labelsOperationLoading = true;
          this.axios({
            method: 'post',
            url: '/work/operation',
            data: values
          }).then(res => {
            if (res.code == 0) {
              this.$message.success(res.msg, 1);
              this.ModalPop = false;
              this.ModalTitle = '';
              this.$refs.table.refresh();
            } else this.$message.warning(res.msg)
          }).catch(() => {
            this.$message.error('服务器发生错误...', 2), this.spinning = false
          }).finally(() => {
            this.labelsOperationLoading = false
          })
        })
      },
      operation({ key },data){
         if(key==1){
             this.ModalPop=true;
             this.ModalTitle='编辑工单';
             setTimeout(() => {
                 this.labelsForm.setFieldsValue({
                    bd_info_id:data.bd_info_id,
                    content:data.content,
                    id:data.id,
                    progress:data.progress,
                    title:data.title,
                    limited_time:moment(new Date(data.limited_time)),
                 });
             }, 0);
             
          }else{
              this.loading = true;
                this.axios({
                    method:'post',
                    url:'/work/deleted',
                    data:{token:this.token,id:data.id}
                }).then(res => {
                    this.loading = false
                    if(res.code==0){
                        this.$message.success(res.msg, 1);
                        this.$refs.table.refresh();
                    }else{
                        this.$message.error(res.msg,2);

                    }
                }).catch(err => {
                    this.$message.error('服务器发生错误...',2);
                }).finally(() => {
                    this.loading = false;
                })
          }
      },
      // 获取小区列表
      getCommunity() {
        this.axios({
          method:'post',
          url:'/parking/getAllCommunityList',
          data:{token:this.token}
        }).then(res => {
          if(res.code === 0){
            this.communityList = res.data;
          }else this.$message.warning(res.msg);
        }).catch(err => {
          this.$message.error('服务器发生错误...');
        })
      },
      // 上传图片
      imageUpload({file,fileList}) {
        let imgs = this.labelsForm.getFieldValue('work_image');
        console.log(imgs);
        if((file.size / 1024 / 1024) > 2) {
          this.$message.warning('图片最大不可超过2M',2);
          return imgs;
        }
        if(file.status === 'removed') {
          for(let [index,item] of imgs.entries()){
            if(item.status === 'removed') imgs.splice(index,1)
          }
          return imgs;
        }
        if(file.status === 'uploading') return fileList;
        if(file.status === 'done'){
          let { code,msg,data } = file.response;
          if(code === 0){
            this.$message.success(msg,1);
            for(let [index,item] of imgs.entries()){
              if(item.uid === file.uid){
                imgs[index] = {uid:data.id,name:data.file_name,url:this.baseURL+'static/uploads/'+data.url}
              }
            }
            return imgs;
          }else {
            this.$message.error(msg,1);
            return imgs;
          }
        }
        if(file.status === 'error'){
          this.$message.error('上传失败',1);
          return imgs;
        }
      },
      // 图片预览
      imgPreview(info) {
        this.previewImage = info.url || info.thumbUrl
        this.imagePreviewVisible = true
      }
    }
  }
</script>

<style lang="less" scoped>
  .index-box{
    background: #ffffff;
    padding: 25px;
    box-sizing: border-box;
    .content-body{
      padding-top:20px;
    }
    .content-head{
      display: flex;
      align-items: center;
      .content-head-title{
        display: inline-block;
        flex: 1 1;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
      .content-head-extra{
        float: right;
      }
    }
  }
</style>